<?php
// $Id$

/**
 * @file
 * User page callbacks for the guild module.
 */

/**
 * Menu callback; Prints a table of all guild members and their ranks by default.
 *
 * @see hook_guild_get_roster()
 */
function guild_roster_render() {
  $game_module = variable_get('guild_game_module', '');
  $players_per_page = variable_get('guild_players_per_page', 50);
  
  // This is where player data can be altered.
  $function = 'guild_get_roster';
  if (module_hook($game_module, 'guild_get_roster')) {
    $function = $game_module . '_guild_get_roster';
  }
  
  $players = $function($players_per_page);
  
  $total_players = db_result(db_query(
    "SELECT COUNT(n.nid) FROM {node} n " .
    "INNER JOIN {guild_member} m ON n.vid = m.vid WHERE m.status <> %d",
    GUILD_PLAYER_HIDDEN
  ));
  
  $inactive_players = db_result(db_query(
    "SELECT COUNT(n.nid) FROM {node} n " .
    "INNER JOIN {guild_member} m ON n.vid = m.vid WHERE m.status = %d",
    GUILD_PLAYER_INACTIVE
  ));
  
  return theme(
    array('guild_roster__' . $game_module, 'guild_roster'),
    $players, $players_per_page, $total_players, $inactive_players
  );
}

/**
 * Returns an array of all players, as determined by the roster filter.
 *
 * @see guild_roster_render()
 */
function guild_get_roster($players_per_page) {
  $players = array();
  $filter = guild_build_filter_query();
  $header = _guild_get_roster_header();
  
  $sql = db_rewrite_sql(
    "SELECT n.nid, n.title, m.status AS guild_status, r.name AS rankName " .
    "FROM {node} n " .
    $filter['join'] .
    "INNER JOIN {guild_member} m ON n.vid = m.vid " .
    "LEFT JOIN {guild_rank} r ON m.rank_id = r.rank_id " .
    $filter['where'] .
    tablesort_sql($header) . ', n.title ASC'
  );
  
  $result = pager_query($sql, $players_per_page, 0, NULL, $filter['args']);
  
  while ($node = db_fetch_object($result)) {
    $player = new stdClass();
    $player->name = $node->title;
    $player->rank = $node->rankName;
    
    $players[$node->nid] = $player;
  }
  
  return $players;
}

/**
 * Returns an array containing the header of the default guild roster table,
 * as expected by theme_table().
 */
function _guild_get_roster_header() {
  return array(
    array('data' => t('Name'), 'field' => 'n.title', 'sort' => 'asc'),
    array('data' => t('Rank'), 'field' => 'r.tier', 'sort' => 'desc')
  );
}
